class Login {
  returnUrl = '';
  constructor() {
    //1- 登录按钮绑定事件
    this.$('.over').addEventListener('click', this.check.bind(this));
        // 设置登录成功后的回跳地址
        let param = location.search;
        if (param) {
          param = param.split('?')[1];
          this.returnUrl = param;
        }
  }
  //2-1 登录数据
  check(){
    //2-1 获取数据
    let form = document.forms.login.elements;
    let username = form.uname.value.trim();
    let password = form.password.value.trim();
    console.log(username, password);
    //2-2 账号密码非空验证
    if (!username) {
      layer.tips('用户名不能为空!', form.uname);
      return;
    }
    if (!password) {
      layer.tips('密码不能为空!', form.password);
      return;
    }
    //2-3 全局axios表头
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    //Authorization字段
    axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
    
    // 2-4发送ajax登录
    let param = `username=${username}&password=${password}`;
    axios.post('http://localhost:8888/users/login', param).then(({ status, data }) => {
      // 判断登录是否成功
      if (status != 200 || data.code != 1) {
        layer.msg('该账号未注册,即将跳转注册页面..');
        setTimeout(function(){
          location.href='./register.html'
        },3000)
        return;
      }

      //2-5 存储token
      localStorage.setItem('token', data.token);
      localStorage.setItem('user_id', data.user.id)
      //2-6 回跳到原来页面,如果returnUrl,为空则调回list,有值则跳回到指定页面
      console.log(this.returnUrl);
      this.returnUrl ? location.assign(this.returnUrl) : location.assign('./list.html');
    })
  }
  // 获取节点的方法
  $(ele) {
    let res = document.querySelectorAll(ele);
    return res.length == 1 ? res[0] : res;
  }
}

new Login;